//
//  RegimenDetailViewController.m
//  味·道
//
//  Created by lanou3g on 15/7/1.
//  Copyright (c) 2015年 WMR. All rights reserved.
//

#import "RegimenDetailViewController.h"
#import "RequestManager.h"
#import "RegimenDetailModel.h"
#import "MaocHeader.h"
#import "RegimenLastViewController.h"
#import "RegimenDetailTableViewCell.h"
#import "LORefresh.h"

static const CGFloat MJDuration = 2.0;

@interface RegimenDetailViewController ()<RequestManagerDelegate,UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,retain)UIButton *backButton;
@property (nonatomic,retain)NSMutableArray *dataSourceArray;//数据源数组
@property (nonatomic,retain)UITableView *mainTableView;//详情列表
@end

@implementation RegimenDetailViewController
- (void)dealloc
{
    self.tag = nil;
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化数组
    self.dataSourceArray = [NSMutableArray array];
    self.view.backgroundColor = [UIColor colorWithRed:0.6 green:0.2 blue:0.5 alpha:1];
    [self createTitleLabel];
    [self requestData:@"http://ibaby.ipadown.com/api/food/food.tips.list.php?p=1&pagesize=20&tags="];
    [self createBackButton];
    [self createMainTableView];
    [self.mainTableView addRefreshWithRefreshViewType:LORefreshViewTypeHeaderDefault refreshingBlock:^{
//        [self.dataSourceArray removeAllObjects];
        [self requestData:@"http://ibaby.ipadown.com/api/food/food.tips.list.php?p=1&pagesize=20&tags="];
    }];
    [self.mainTableView addRefreshWithRefreshViewType:(LORefreshViewTypeFooterDefault) refreshingBlock:^{
        static int i = 2;
        if (i<=20) {
            NSString *str = [NSString stringWithFormat:@"http://ibaby.ipadown.com/api/food/food.tips.list.php?p=%d&pagesize=20&tags=",i];
            NSLog(@"%@",str);
            [self requestData:str];
            [self.mainTableView reloadData];
            i++;
        }else{
            
            // 拿到当前的上拉刷新控件，变为没有更多数据的状态
            [self.mainTableView.defaultFooter endRefreshing];
        }
    }];
    
}
//请求参数
-(void)requestData:(NSString *)urlString{
    NSString *url = urlString;
    self.tag = [self.tag stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    url = [url stringByAppendingString:self.tag];
    RequestManager *request = [[RequestManager alloc] initWithRequestURL:url requestModel:GET requestParameter:nil];
    request.delegate = self;
    [request startRequest];
}
#pragma mark - RequestManagerDelegate
-(void)requestDidFinishWithData:(NSData *)data{
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves) error:nil];
    NSArray *resultsArray = dic[@"results"];
    for (NSDictionary *dict in resultsArray) {
        RegimenDetailModel *model = [[RegimenDetailModel alloc] init];
        [model setValuesForKeysWithDictionary:dict];
        [self.dataSourceArray addObject:model];
        [model release];
    }
    NSLog(@"%ld",self.dataSourceArray.count);
    [self.mainTableView reloadData];//刷新数据
    [self.mainTableView.defaultHeader endRefreshing];
    [self.mainTableView.defaultFooter endRefreshing];
}
-(void)requestError:(NSError *)error{
    NSLog(@"%@",error);
}
#pragma mark - 创建返回键,标题Label
-(void)createBackButton{
    UIButton *backButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    backButton.frame = CGRectMake(15, 30, 50, 18);
    [backButton setTitle:@"返回" forState:(UIControlStateNormal)];
    [backButton addTarget:self action:@selector(backToList:) forControlEvents:(UIControlEventTouchUpInside)];
    self.backButton = backButton;
    [self.view addSubview:self.backButton];
}
//返回上一页面
-(void)backToList:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)createTitleLabel{
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(150, 30, 80, 20)];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.text = self.tag;
    titleLabel.font = [UIFont boldSystemFontOfSize:18.0f];
    [self.view addSubview:titleLabel];
    [titleLabel release];
}
#pragma mark - 创建mainTableView
-(void)createMainTableView{
    UITableView *mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 60, SCREEN_WIDTH, SCREEN_HEIGHT) style:(UITableViewStylePlain)];
    mainTableView.delegate = self;
    mainTableView.dataSource = self;
    mainTableView.backgroundColor = [UIColor whiteColor];
    mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [mainTableView registerClass:[RegimenDetailTableViewCell class] forCellReuseIdentifier:@"list"];
    
    //没有之后下面是空白的
//    UIView *view = [[UIView alloc] init];
//    mainTableView.tableFooterView = view;
    self.mainTableView = mainTableView;
    [self.view addSubview:self.mainTableView];
    [mainTableView release];
}
#pragma mark - 下拉刷新，上拉加载



#pragma mark - UITableViewDelegate,UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSourceArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RegimenDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"list" forIndexPath:indexPath];
    RegimenDetailModel *model = self.dataSourceArray[indexPath.row];
    cell.label.text = model.title;
    cell.numberLabel.text = [NSString stringWithFormat:@"%ld",indexPath.row+1];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    RegimenLastViewController *regimenLVC = [[RegimenLastViewController alloc] init];
    RegimenDetailModel *model = self.dataSourceArray[indexPath.row];
    regimenLVC.ID = model.ID;
    [self.navigationController pushViewController:regimenLVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
